package org.benetech.reader;

import java.io.IOException;
import java.util.ArrayList;

import org.benetech.reader.parser.HttpResponseAPI;
import org.benetech.reader.parser.ParserAPI;
import org.benetech.reader.representations.Book;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ResultsListActivity extends ListActivity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      ListView listView = (ListView) findViewById(R.id.mylist);
      ArrayList<Book> books = null;
      try {
         String url = "https://api.bookshare.org/book/searchFTS/"
               + BenetechReaderActivity.searchStr
               + "/page/1/limit/10/format/json?api_key=mzfgnmsjq9hev4dhf3ag6yqs";
         books = ParserAPI.parseSearchFTS(HttpResponseAPI.getResponseText(url));
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      super.onCreate(savedInstanceState);
      String[] titles = new String[books.size()];

      for (int i = 0; i < books.size(); i++)
         titles[i] = books.get(i).getTitle();
      setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, titles));

      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View view,
               int position, long id) {
            // details page can be added
            Toast.makeText(getApplicationContext(),
                  ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
         }
      });
   }
}
